function printArraySpirally(arr) {
  let result = []
  let top = 0, bottom = arr.length - 1, left = 0, right = arr[0].length - 1
  let dir = 0

  while (top <= bottom && left <= right) {
    if (dir === 0) { // move right
      for (let i = left; i <= right; i++) {
        result.push(arr[top][i])
      }
      top++
    } else if (dir === 1) { // move down
      for (let i = top; i <= bottom; i++) {
        result.push(arr[i][right])
      }
      right--
    } else if (dir === 2) { // move left
      for (let i = right; i >= left; i--) {
        result.push(arr[bottom][i])
      }
      bottom--
    } else if (dir === 3) { // move up
      for (let i = bottom; i >= top; i--) {
        result.push(arr[i][left])
      }
      left++
    }
    dir = (dir + 1) % 4
  }

  return result.join(',')
}

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
console.log(printArraySpirally(arr))
